package org.idea.qiyu.common;

import sun.misc.Cleaner;
import sun.nio.ch.DirectBuffer;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.lang.reflect.Method;
import java.nio.Buffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.Scanner;

/**
 * @Author linhao
 * @Date created in 9:05 上午 2021/5/24
 */
public class SystemUtil {


    /**
     * 零拷贝的测试案例
     *
     * @param args
     */
    public static void main(String[] args) {
        File file = new File("/Users/linhao/IdeaProjects/qiyu-framework-gitee/qiyu-framework/qiyu-framework-common/src/main/resources/test_compile_tempfile.txt");
        long len = file.length();
        byte[] bs = new byte[(int) len];
        RandomAccessFile randomAccessFile = null;
        FileChannel fileChannel = null;
        try {
            randomAccessFile = new RandomAccessFile(file, "r");
            fileChannel = randomAccessFile
                    .getChannel();
            MappedByteBuffer mappedByteBuffer = fileChannel.map(FileChannel.MapMode.READ_ONLY, 0, len);
            for (int offset = 0; offset < len; offset++) {
                byte b = mappedByteBuffer.get();
                bs[offset] = b;
            }
            Scanner scan = new Scanner(new ByteArrayInputStream(bs)).useDelimiter(" ");
            while (scan.hasNext()) {
                System.out.println(scan.next() + " ");
            }
            mappedByteBuffer.clear();
            unmap(mappedByteBuffer);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (randomAccessFile != null) {
                try {
                    randomAccessFile.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (fileChannel != null) {
                try {
                    fileChannel.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private static void unmap(MappedByteBuffer bb) {
        Cleaner cl = ((DirectBuffer)bb).cleaner();
        if (cl != null){
            cl.clean();
        }
    }

}
